# 导包
import pymysql


# 数据库工具类
class DBTools:
    # 建立连接的私有方法--类方法
    @classmethod
    def __get_conn(cls):
        conn = pymysql.connect(host='localhost', port=3306, user='root', password='root', database='advanced',
                               charset='utf8')
        return conn

    # 查询一条记录--类方法
    @classmethod
    def select_one(cls, sql):
        conn = None
        cursor = None
        res = None
        try:
            # 调用 自己封装的建立的方法,得到一个连接对象
            conn = cls.__get_conn()
            # 获取游标
            cursor = conn.cursor()
            # 执行用户指定的查询SQL
            cursor.execute(sql)
            # 获取结果
            res = cursor.fetchone()  # 只获取一条
        except Exception as err:
            print("执行SQL查询一条记录时,报错:", str(err))
        finally:
            # 关闭资源
            cursor.close()
            conn.close()
            # 返回查询结果给用户
            return res

    # 增删改
    @classmethod
    def uid_db(cls, sql):
        conn = None
        cursor = None
        try:
            conn = cls.__get_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            # 没有异常,提交事务
            conn.commit()
            print("受影响的行数:", conn.affected_rows())
        except Exception as err:
            print('执行SQL增删改数据库,报错:', str(err))
        finally:
            cursor.close()
            conn.close()


if __name__ == '__main__':
    # 使用类名.方法名 调用类方法
    # res = DBTools.select_one('select * from student;')
    # print("res = ",res) # 接收的结果,打印查看
    insert_sql = 'insert into student values(17,"itsrc-021","小王",20,11,200)'
    DBTools.uid_db(insert_sql)